package sipus.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.Criteria;
import org.hibernate.EntityMode;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.zkoss.breeze.Themes;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.sys.ExecutionsCtrl;
import org.zkoss.zul.A;
import org.zkoss.zul.Bandbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.Decimalbox;
import org.zkoss.zul.Html;
import org.zkoss.zul.Image;
import org.zkoss.zul.Include;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Tabbox;
import org.zkoss.zul.Tabpanel;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Tree;
import org.zkoss.zul.Treechildren;
import org.zkoss.zul.Treeitem;
import org.zkoss.zul.Vbox;
import org.zkoss.zul.Window;

import sipus.database.hibernate.HibernateUtil;
import sipus.database.model.AccessedUsers;
import sipus.database.model.CommonVO;
import sipus.database.model.DetailLogLogin;
import sipus.database.model.LogLogin;
import sipus.database.model.Menu;
import sipus.database.model.OnlineUsers;
import sipus.database.model.Tbmuser;


public class Common {

	public static String ROOT = "/sipus";
	public static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"dd-MM-yyyy HH:mm");
	public static SimpleDateFormat dateFormat3 = new SimpleDateFormat(
			"dd-MM-yyyy HH:mm:ss");
	public static SimpleDateFormat dateFormat2 = new SimpleDateFormat(
			"dd MMMM yyyy");

	public static SimpleDateFormat databaseDateFormat = new SimpleDateFormat(
			"yyyy-MM-dd");

	public static NumberFormat numberFormat = NumberFormat
			.getNumberInstance(new Locale("in", "ID"));
	public static int MAX_RESULT = 250;
	public static int MAX_RESULT_100 = 100;
	public static int MAX_RESULT_50 = 50;
	public static String ROOT_UPLOAD;

	public static final String DES_PASS_PHRASE = "sirs";
	public static DesEncrypter desEncrypter = new DesEncrypter(
			Common.DES_PASS_PHRASE);

	public static Long increments = 0L;

	@SuppressWarnings("rawtypes")
	public static void initSequence(Class clazz, String squenceName) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		ClassMetadata metadata = HibernateUtil.getSessionFactory()
				.getClassMetadata(clazz);
		Number s = (Number) session
				.createCriteria(clazz)
				.setProjection(
						Projections.max(metadata.getIdentifierPropertyName()))
				.uniqueResult();
		if (s == null) {
			s = 1;
		}
		Integer number = s.intValue();
		String sql = "ALTER SEQUENCE tms_jua." + squenceName + " RESTART WITH "
				+ (++number);
		session.getTransaction().begin();
		session.createSQLQuery(sql).executeUpdate();
		session.getTransaction().commit();
		session.disconnect();
		session.close();
	}

	public static Combobox createComboHari() {
		Combobox hari = new Combobox();
		for (String h : Common.haris) {
			Comboitem comboitem = new Comboitem();
			comboitem.setLabel(h);
			comboitem.setValue(h);
			hari.appendChild(comboitem);
		}
		return hari;
	}

	@SuppressWarnings("unchecked")
	public static void insertToTab(final Tabbox iframe, final Menu menu,
			final LogLogin login) {
		List<Tab> tabs = iframe.getTabs().getChildren();
		boolean ada = false;
		for (Tab tab : tabs) {
			if (tab.getLabel().equalsIgnoreCase(menu.getLabel())) {
				ada = true;
				tab.setSelected(true);
				break;
			}
		}
		if (!ada) {
			final Tab tab = new Tab(menu.getLabel());
			tab.addEventListener("onClick", new EventListener() {

				@Override
				public void onEvent(Event arg0) throws Exception {
					System.out.println("============================= "
							+ tab.getLabel() + " ================ clicked");
					DetailLogLogin detailLogLogin = new DetailLogLogin();
					detailLogLogin.setKeterangan(menu.getLabel());
					detailLogLogin.setWaktu(new Date());
					detailLogLogin.setLogLogin(login);
					detailLogLogin.setHalaman(menu.getUrl());
					HibernateUtil.currentSession().save(detailLogLogin);
					Sessions.getCurrent().setAttribute("detailLogLogin",
							detailLogLogin);
				}
			});
			tab.setClosable(true);
			tab.setSelected(true);
			iframe.getTabs().appendChild(tab);
			Tabpanel tabpanel = new Tabpanel();
			Include include = new Include(menu.getUrl().trim());
			include.setWidth("100%");
			include.setHeight("100%");
			tabpanel.appendChild(include);
			iframe.getTabpanels().appendChild(tabpanel);
		}
	}

	@SuppressWarnings("unchecked")
	public static void insertToTab(final Tabbox iframe, final Menu menu,
			final Window window, final LogLogin login) {
		window.setHeight("100%");
		window.setWidth("100%");
		List<Tab> tabs = iframe.getTabs().getChildren();
		boolean ada = false;
		for (Tab tab : tabs) {
			if (tab.getLabel().equalsIgnoreCase(menu.getLabel())) {
				ada = true;
				tab.setSelected(true);
				break;
			}
		}
		if (!ada) {
			final Tab tab = new Tab(menu.getLabel());
			tab.addEventListener("onClick", new EventListener() {

				@Override
				public void onEvent(Event arg0) throws Exception {
					System.out.println("============================= "
							+ tab.getLabel() + " ================ clicked");
					DetailLogLogin detailLogLogin = new DetailLogLogin();
					detailLogLogin.setKeterangan(menu.getLabel());
					detailLogLogin.setWaktu(new Date());
					detailLogLogin.setLogLogin(login);
					detailLogLogin.setHalaman(menu.getUrl());
					HibernateUtil.currentSession().save(detailLogLogin);
					Sessions.getCurrent().setAttribute("detailLogLogin",
							detailLogLogin);
				}
			});
			tab.setClosable(true);
			tab.setSelected(true);
			iframe.getTabs().appendChild(tab);
			Tabpanel tabpanel = new Tabpanel();
			tabpanel.appendChild(window);
			iframe.getTabpanels().appendChild(tabpanel);
		}
	}

	public static void setUserAccess(HttpServletRequest request) {
		HttpSession httpSession = (HttpSession) Sessions.getCurrent()
				.getNativeSession();
		String req = request.getRequestURL().toString();
		req = req.replaceAll("http://", "");
		req = req.split(":")[0];
		req = req.split("/")[0];
		Session mySession = HibernateUtil.currentSession();
		AccessedUsers accessedUsers = (AccessedUsers) mySession
				.createCriteria(AccessedUsers.class)
				.add(Restrictions.eq("nama", httpSession.getId()))
				.setMaxResults(1).uniqueResult();
		if (accessedUsers == null) {
			accessedUsers = new AccessedUsers();
			accessedUsers.setNama(httpSession.getId());
			accessedUsers.setHost(req);
			mySession.save(accessedUsers);
		}
		Sessions.getCurrent().setAttribute("accessedUsers", accessedUsers);
	}

	public static void setFooterText(HttpServletRequest request, A a) {
		String req = request.getRequestURL().toString();
		req = req.replaceAll("http://", "");
		req = req.split(":")[0];
		req = req.split("/")[0];

		String content_path = request.getContextPath().replace("/", "");
		if (content_path.contains("contoh")) {
			a.setLabel("\u00a9 " + Calendar.getInstance().get(Calendar.YEAR)
					+ " Universitas Anda");
			a.setHref("http://universitas.anda.com");
		} else if (req.contains("fst")) {
			a.setLabel("\u00a9 "
					+ Calendar.getInstance().get(Calendar.YEAR)
					+ " Fakultas Sains dan Teknologi, Universitas Islam Negeri Syarif Hidayatullah Jakarta");
			a.setHref("http://fst.uinjkt.ac.id/fstportal");
		} else {
			a.setLabel("\u00a9 " + Calendar.getInstance().get(Calendar.YEAR)
					+ " Universitas Islam Negeri Syarif Hidayatullah Jakarta");
		}
	}

	public static void removeUserAccess() {
		HttpSession httpSession = (HttpSession) Sessions.getCurrent()
				.getNativeSession();

		Session mySession = HibernateUtil.currentSession();
		AccessedUsers accessedUsers = (AccessedUsers) mySession
				.createCriteria(AccessedUsers.class)
				.add(Restrictions.eq("nama", httpSession.getId()))
				.setMaxResults(1).uniqueResult();
		if (accessedUsers != null) {
			mySession.delete(accessedUsers);
		}
	}

	public static void setting(Image header, A footer, Vbox menubar,
			Html pemberitahuan) throws Exception {
		HttpServletRequest request = (HttpServletRequest) ExecutionsCtrl
				.getCurrent().getNativeRequest();
		String req = request.getRequestURL().toString();
		req = req.replaceAll("http://", "");
		req = req.split(":")[0];
		req = req.split("/")[0];

		// String content_path = request.getContextPath().replace("/", "");

		// if (req.contains("fst") || content_path.contains("contoh")) {
		Themes.setTheme(ExecutionsCtrl.getCurrent(), "breeze");
		// } else {
		// Themes.setTheme(ExecutionsCtrl.getCurrent(), "blue");
		// }

		if (menubar != null) {
			menubar.setVisible(req.equalsIgnoreCase("sipus.uinjkt.ac.id")
					|| req.equalsIgnoreCase("localhost"));
		}

		// if (pemberitahuan != null) {
		// String content = "<ol><li>Gunakan   browser   Mozilla  "
		// + "Firefox   untuk hasil   terbaik</li>  "
		// + "<li>Khusus   mahasiswa,   demi alasan  "
		// + "kemanan,   segera ganti   password   lama  "
		// + "anda</li>   <li>Pada   saat   memasukkan  "
		// + "biodata,   masukkan   alamat email  "
		// + "secara   lengkap,   alamat email   ini  "
		// + "digunakan   untuk   melakukan  "
		// + "verifikasi   (misalnya   lupa  "
		// + "password)</li>   <li>Jika   terjadi  "
		// + "masalah,   harap segera   hubungi  "
		// + "puskom@uinjkt.ac.id</li>   </ol>";
		// if (req.contains("fst")) {
		// content = "<ol><li>Gunakan   browser   Mozilla  "
		// + "Firefox   untuk hasil   terbaik</li>  "
		// + "<li>Khusus   mahasiswa,   demi alasan  "
		// + "kemanan,   segera ganti   password   lama  "
		// + "anda</li>   <li>Pada   saat   memasukkan  "
		// + "biodata,   masukkan   alamat email  "
		// + "secara   lengkap,   alamat email   ini  "
		// + "digunakan   untuk   melakukan  "
		// + "verifikasi   (misalnya   lupa  "
		// + "password)</li>   <li>Jika   terjadi  "
		// + "masalah,   harap segera   hubungi  "
		// + " pusdatin@fstuinjkt.net atau puskom@uinjkt.ac.id</li>   </ol>";
		// } else if (content_path.contains("contoh")) {
		// content = "<ol><li>Gunakan   browser   Mozilla  "
		// + "Firefox   untuk hasil   terbaik</li>  "
		// + "<li>Khusus   mahasiswa,   demi alasan  "
		// + "kemanan,   segera ganti   password   lama  "
		// + "anda</li>   <li>Pada   saat   memasukkan  "
		// + "biodata,   masukkan   alamat email  "
		// + "secara   lengkap,   alamat email   ini  "
		// + "digunakan   untuk   melakukan  "
		// + "verifikasi   (misalnya   lupa  "
		// + "password)</li>   <li>Jika   terjadi  "
		// + "masalah,   harap segera   hubungi  "
		// + "admin@universitas.anda.ac.id</li>   </ol>";
		// }
		if (pemberitahuan != null)
			pemberitahuan.setContent("");
		// }
		//
		// System.out.println("URL = " + req);
		// if (header != null) {
		// File file = new File(Sessions.getCurrent().getWebApp()
		// .getRealPath("/img/" + req + "_header.png"));
		// if (content_path.contains("contoh")) {
		// file = new File(Sessions.getCurrent().getWebApp()
		// .getRealPath("/img/contoh_header.png"));
		// }
		// if (file.exists()) {
		// AImage aImage = new AImage(file);
		// header.setContent(aImage);
		// }
		// }
		//
		// if (footer != null) {
		// setFooterText((HttpServletRequest) ExecutionsCtrl.getCurrent()
		// .getNativeRequest(), footer);
		// }
	}

	public static Boolean isNowSemensterGanjil() {
		Integer bulan = Calendar.getInstance().get(Calendar.MONTH);
		System.out.println(bulan);
		return bulan >= 5;

	}

	public static Tbmuser getCurrentFromSpringUser() {
		return getCurrentFromSpringUser((HttpServletRequest) ExecutionsCtrl
				.getCurrent().getNativeRequest());
	}

	public static Tbmuser getCurrentFromSpringUser(HttpServletRequest request) {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		UserDetails userDetails = null;
		if (principal instanceof UserDetails) {
			userDetails = (UserDetails) principal;
		}
		String req = request.getRequestURL().toString();
		req = req.replaceAll("http://", "");
		req = req.split(":")[0];
		req = req.split("/")[0];
		setUserAccess(request);
		AccessedUsers accessedUsers = (AccessedUsers) Sessions.getCurrent()
				.getAttribute("accessedUsers");
		String userName = userDetails.getUsername();

		Session session = HibernateUtil.currentSession();

		Tbmuser users = (Tbmuser) session.createCriteria(Tbmuser.class)
				.add(Restrictions.eq("userId", userName)).setMaxResults(1)
				.uniqueResult();
		Sessions.getCurrent().setAttribute("usersTemp", users);

		LogLogin login = (LogLogin) session.createCriteria(LogLogin.class)
				.add(Restrictions.eq("nama", userName))
				.add(Restrictions.isNull("logout"))
				.add(Restrictions.eq("success_status", true))
				.addOrder(Order.desc("id")).setMaxResults(1).uniqueResult();
		if (login == null) {
			ExecutionsCtrl.getCurrent().sendRedirect("/logoff");
			return null;
		}

		Sessions.getCurrent().setAttribute("login", login);

		OnlineUsers onlineUsers = (OnlineUsers) session
				.createCriteria(OnlineUsers.class)
				.add(Restrictions.ilike("nama", users.getUserId().trim(),
						MatchMode.EXACT)).setMaxResults(1).uniqueResult();
		if (onlineUsers == null) {
			onlineUsers = new OnlineUsers();
		}

		onlineUsers.setAccessedUsers(accessedUsers);
		onlineUsers.setTbmuser(users);
		onlineUsers.setNama(users.getUserId());
		onlineUsers.setHost(req);
		onlineUsers.setLogin(login);
		session.saveOrUpdate(onlineUsers);

		return users;

	}

	@SuppressWarnings("unchecked")
	public static void encripSemua() {
		Session session = HibernateUtil.currentSession();
		List<Tbmuser> tbmusers = session
				.createCriteria(Tbmuser.class)
				.add(Restrictions.or(Restrictions.isNull("is_encripted"),
						Restrictions.eq("is_encripted", false))).list();
		for (Tbmuser tbmuser : tbmusers) {
			tbmuser.setIs_encripted(true);
			tbmuser.setUserPassword(desEncrypter.encrypt(tbmuser
					.getUserPassword()));
			session.update(tbmuser);
		}
	}

	public static String[] haris = { "Minggu", "Senin", "Selasa", "Rabu",
			"Kamis", "Jum'at", "Sabtu" };

	private static Long autoGeneratorId = 0L;

	public static Locale locale = new Locale("in", "ID");

	static {
		numberFormat.setMaximumFractionDigits(2);
	}

	public static Session getManualSession() {
		return HibernateUtil.currentSession();
	}

	public static FileInputStream createInputStreamFromFile(Blob blob) {
		InputStream inputStream = null;
		FileInputStream fileInputStream = null;
		try {
			inputStream = blob.getBinaryStream();
			File file = Common.getCreateRandomFile();
			FileOutputStream outputStream = new FileOutputStream(file);
			int c;
			while ((c = inputStream.read()) != -1) {
				outputStream.write(c);
			}
			outputStream.close();
			inputStream.close();
			fileInputStream = new FileInputStream(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileInputStream;
	}

	public static File getCreateRandomFile() {
		File myFile = new File(
				("/opt/file_erp/" + (new Date().getTime()) + "_" + (++increments)));
		myFile.getParentFile().mkdirs();
		return myFile;
	}

	public static Tbmuser getCurrentUser() {
		Tbmuser users = (Tbmuser) (Sessions.getCurrent() == null ? null
				: Sessions.getCurrent().getAttribute("usersTemp"));
		return users;
	}

	public static Menu getCurrentMenu() {
		Menu menu = (Menu) Sessions.getCurrent().getAttribute("currentMenu");
		return menu;
	}

	public static String getGeneratedBarCode() {
		String str = "" + Calendar.getInstance().getTimeInMillis() + ""
				+ (++autoGeneratorId);
		Long lg = Long.parseLong(str);
		return Long.toHexString(lg).toUpperCase();
	}

	public static Combobox generateJam(Combobox combobox) {
		if (combobox == null) {
			combobox = new Combobox();
		}

		return combobox;
	}

	public static String generateSingkatan(String asal) {
		if (asal == null || asal.trim().equals("")) {
			return "";
		}
		String[] ss = asal.split(" ");
		String hasil = "";
		for (String s : ss) {
			if (s.trim().equals(""))
				continue;
			hasil += s.trim().substring(0, 1).toUpperCase();
		}
		return hasil;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Boolean isMenuExist(Tree tree, Menu menu) {
		List child = tree.getChildren();
		for (Object o : child) {
			System.out.println(o.getClass().getName());
			if (o instanceof Treechildren) {
				Treechildren treechildren = (Treechildren) o;
				List<Treeitem> treeitems = treechildren.getChildren();
				for (Treeitem treeitem : treeitems) {
					if (menu.getUrl() != null && treeitem.getValue() != null
							&& menu.getUrl().trim().equals(treeitem.getValue())) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static Boolean isMenuExist(Collection<Menu> menus, Menu menu) {

		for (Menu my : menus) {
			if (menu.getUrl() != null && my.getUrl() != null
					&& menu.getUrl().trim().equals(my.getUrl().trim())) {
				return true;
			}
		}

		return false;
	}

	public static Tbmuser getTbmuser() {
		return (Tbmuser) Sessions.getCurrent().getAttribute("users");
	}

	@SuppressWarnings("rawtypes")
	public static void initCombos(Combobox[] comboboxs, String[] properties,
			Class[] classes) {
		for (int i = 0; i < comboboxs.length; i++) {
			insertCombo(comboboxs[i], properties[i], classes[i]);
		}
	}

	@SuppressWarnings({ "rawtypes" })
	public static void initCombos(Combobox[] comboboxs, String[] properties,
			Class[] classes, Criterion[] criterions) {
		for (int i = 0; i < comboboxs.length; i++) {
			insertCombo(comboboxs[i], properties[i], classes[i], criterions[i]);
		}
	}

	@SuppressWarnings("rawtypes")
	public static void insertCombo(Combobox combobox, String property,
			Class clazz, Criterion... criterions) {
		Criteria criteria = HibernateUtil.currentSession()
				.createCriteria(clazz);
		if (criterions != null) {
			for (Criterion criterion : criterions) {
				if (criterion != null) {
					criteria.add(criterion);
				}
			}
		}
		List list = criteria.list();
		insertComboItems(combobox, property, list);
	}

	public static void insertCombo(Combobox combobox, String property,
			Class<?> clazz, Criterion criterion) {
		Criteria criteria = HibernateUtil.currentSession()
				.createCriteria(clazz);
		criteria.add(criterion);
		List<?> list = criteria.list();
		insertComboItems(combobox, property, list);
	}

	public static void insertCombo(Combobox combobox, String property,
			String deskripsi, Class<?> clazz, Criterion criterion) {
		Criteria criteria = HibernateUtil.currentSession()
				.createCriteria(clazz);
		criteria.add(criterion);
		List<?> list = criteria.list();
		insertComboItems(combobox, property, deskripsi, list);
	}

	public static void insertCombo(Combobox combobox, String property,
			Class<?> clazz) {
		if (combobox == null)
			return;
		Criteria criteria = HibernateUtil.currentSession()
				.createCriteria(clazz);

		List<?> list = criteria.list();
		insertComboItems(combobox, property, list);
	}

	public static void insertCombo(Combobox combobox, String property,
			String deskripsi, Class<?> clazz) {
		if (combobox == null)
			return;
		Criteria criteria = HibernateUtil.currentSession()
				.createCriteria(clazz);

		List<?> list = criteria.list();
		insertComboItems(combobox, property, deskripsi, list);
	}

	public static Boolean checkValidasi(Object... property) throws Exception {
		for (Object o : property) {
			if (o instanceof String) {
				if (o == null || o.toString().trim().equals("")) {
					Messagebox.show("Field harus dilengkapi");
					return false;
				}
			}
			if (o instanceof Textbox) {
				Textbox oo = (Textbox) o;
				if (oo.getValue().trim().equals("")) {
					Messagebox.show("Field ini harus diisi");
					oo.focus();
					return false;
				}
			}
			if (o instanceof Bandbox) {
				Bandbox oo = (Bandbox) o;
				if (oo.getValue().trim().equals("")) {
					Messagebox.show("Field ini harus diisi");
					oo.focus();
					return false;
				}
			}
			if (o instanceof Combobox) {
				Combobox oo = (Combobox) o;
				if (oo.getSelectedItem() == null
						|| oo.getSelectedItem().getValue() == null) {
					Messagebox.show("Field ini harus diisi");
					oo.focus();
					return false;
				}
			}

			if (o instanceof Decimalbox) {
				Decimalbox oo = (Decimalbox) o;
				if (oo.getValue() == null || oo.getValue().equals("")) {
					Messagebox.show("Field ini harus diisi");
					oo.focus();
					return false;
				}
			}

		}
		return true;
	}

	public static void clear(Component comp) {
		if (comp == null || comp.getChildren() == null)
			return;
		int list = comp.getChildren().size();
		for (int i = 0; i < list; i++) {
			((Component) comp.getChildren().get(0)).detach();
		}
	}

	public static void insertComboItems(Combobox combo, String property,
			List<?> items) {
		Common.clear(combo);
		if (items.size() == 0)
			return;
		Class<? extends Object> clazz = items.get(0).getClass();
		ClassMetadata metadata = null;
		if (!clazz.equals(CommonVO.class)) {
			metadata = HibernateUtil.getClassMetadata(clazz);
		}
		for (Object o : items) {
			Comboitem comboitem = new Comboitem();
			if (o instanceof CommonVO) {
				CommonVO oo = (CommonVO) o;
				comboitem.setLabel(oo.getName());
				comboitem.setValue(oo.getId());
			} else {
				try {
					comboitem.setLabel(property.equals("") ? o + "" : ""
							+ metadata.getPropertyValue(o, property,
									EntityMode.POJO));
				} catch (Exception e) {
					comboitem.setLabel(property.equals("") ? o + "" : ""
							+ metadata.getIdentifier(o, EntityMode.POJO));
				}
				comboitem.setValue(o);
			}
			combo.appendChild(comboitem);
		}
	}

	public static void insertComboItems(Combobox combo, String property,
			String deskripsi, List<?> items) {
		Common.clear(combo);
		if (items.size() == 0)
			return;
		Class<? extends Object> clazz = items.get(0).getClass();
		ClassMetadata metadata = null;
		if (!clazz.equals(CommonVO.class)) {
			metadata = HibernateUtil.getClassMetadata(clazz);
		}
		for (Object o : items) {
			Comboitem comboitem = new Comboitem();
			if (o instanceof CommonVO) {
				CommonVO oo = (CommonVO) o;
				comboitem.setLabel(oo.getName());
				comboitem.setDescription(oo.getName1());
				comboitem.setValue(oo.getId());
			} else {
				comboitem.setLabel(property.equals("") ? o + "" : ""
						+ metadata.getPropertyValue(o, property,
								EntityMode.POJO));
				comboitem.setDescription(deskripsi.equals("") ? o + "" : ""
						+ metadata.getPropertyValue(o, deskripsi,
								EntityMode.POJO));
				comboitem.setValue(o);
			}
			combo.appendChild(comboitem);
		}
	}

	@SuppressWarnings("unchecked")
	public static void selectComboItem(Combobox combo, Object value) {
		if (value == null) {
			combo.setSelectedItem(null);
			return;
		}

		List<Comboitem> list = combo.getItems();
		ClassMetadata metadata = HibernateUtil.getClassMetadata(value
				.getClass());
		Serializable identityvalue = null;
		if (!(value instanceof String) && !(value instanceof Integer)
				&& !(value instanceof Double) && !(value instanceof Date)) {
			try {
				identityvalue = metadata.getIdentifier(value, EntityMode.POJO);
			} catch (Exception e) {
				return;
			}
		}

		for (Comboitem comboitem : list) {
			if ((value instanceof String) || (value instanceof Integer)
					|| (value instanceof Double) || (value instanceof Date)) {
				// System.out.println("value = " + value
				// + ", comboitem.getValue() = " + comboitem.getValue());
				if (value.equals(comboitem.getValue())) {
					combo.setSelectedItem(comboitem);
				}
			} else {
				try {
					Serializable id = metadata.getIdentifier(
							comboitem.getValue(), EntityMode.POJO);
					// System.out.println("identityvalue = " + identityvalue
					// + ", id = " + id);

					if (identityvalue.equals(id)) {
						combo.setSelectedItem(comboitem);
					}
				} catch (Exception e) {
				}
			}
		}
	}

	public static Boolean createZip(List<String> filesName,
			List<File> filenames, File outFilename) {
		if (filenames.size() == 0) {
			return false;
		}
		// These are the files to include in the ZIP file

		// Create a buffer for reading the files
		byte[] buf = new byte[1024];

		try {
			outFilename.createNewFile();
			// Create the ZIP file
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
					outFilename));

			int i = 0;
			// Compress the files
			for (File filename : filenames) {
				FileInputStream in = new FileInputStream(filename);

				// Add ZIP entry to output stream.
				out.putNextEntry(new ZipEntry(filesName.get(i)));

				// Transfer bytes from the file to the ZIP file
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}

				// Complete the entry
				out.closeEntry();
				in.close();
				i++;
			}

			// Complete the ZIP file
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
